package api

import (
	"gitee.com/zhaokangming/tiny-ticktok/model"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/constants"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/auth"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/convert"
	"gitee.com/zhaokangming/tiny-ticktok/service"

	"github.com/gin-gonic/gin"
)

// CommentListResponse comment list response
type CommentListResponse struct {
	model.Response
	CommentList []model.Comment `json:"comment_list,omitempty"`
}

// CommentAction create or delete a comment
func CommentAction(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	action, ok := c.GetQuery("action_type")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	vid, ok := c.GetQuery("video_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	if action == constants.Action {
		content, ok := c.GetQuery("comment_text")
		if !ok {
			app.WriteResponse(c, errcode.ErrParamTypeError, nil)
			return
		}

		err := service.CreateComment(c, claims.ID, convert.StrTo(vid).MustInt64(), content)
		app.WriteResponse(c, err, nil)
		return
	}

	if action == constants.ActionCancel {
		cid, ok := c.GetQuery("comment_id")
		if !ok {
			app.WriteResponse(c, errcode.ErrParamTypeError, nil)
			return
		}

		err := service.DeleteComment(c, claims.ID, convert.StrTo(cid).MustInt64())
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, errcode.ErrParamTypeError, nil)
}

// CommentList get all comments of a video
func CommentList(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	vid, ok := c.GetQuery("video_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	res, err := service.MGetComments(c, claims.ID, convert.StrTo(vid).MustInt64())
	app.WriteResponse(c, err, res)
}
